﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;


using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using publicLibrary;

namespace asMeishi.web.Models
{
    using Classes;
    /// <summary>
    /// 用户基础类(数据表)
    /// </summary>
    public class user : MongoDocument
    {

        #region 基本属性

        /// <summary>
        /// 用户名称
        /// </summary>
        //[Required] //必填字段
        //[DataType(DataType.)] //必须是email地址
        //[Display(Name = "登陆用户名（您的Email地址）")]
        public string name { get; set; }

        /// <summary>
        /// 登录账号(email地址)
        /// </summary>
        //[Required] //必填字段
        //[DataType(DataType.EmailAddress)] //必须是email地址
        //[Display(Name = "登陆用户名（您的Email地址）")]        
        public string email { get; set; }
        /// <summary>
        /// 密码(MD5加密)
        /// </summary>
        public string password { get; set; }

        #endregion

        #region 复杂属性

        /// <summary>
        /// 性别
        /// </summary>
        public string sex { get; set; }
        /// <summary>
        /// 生日
        /// </summary>
        public DateTime birth { get; set; }
        /// <summary>
        /// QQ号
        /// </summary>
        public string QQ { get; set; }
        /// <summary>
        /// MSN号
        /// </summary>
        public string msn { get; set; }
        /// <summary>
        /// 居住地编码
        /// </summary>
        public string addressNum { get; set; }
        //public string address_province { get; set; }//省
        //public string address_city { get; set; }//城市
        //public string address_area { get; set; }//区

        /// <summary>
        /// 最后登录时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime laterDate { get; set; }
        /// <summary>
        /// 注册时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime regDate { get; set; }
        /// <summary>
        /// 级别(准备弃用？)huohhf
        /// </summary>
        public int limit { get; set; }
        /// <summary>
        /// 用户组(准备弃用？)huohhf
        /// </summary>
        public string group { get; set; }

        /// <summary>
        /// 扩展
        /// </summary>
        public List<string> ext { get; set; }

        #endregion

        #region 扩展属性

        /// <summary>
        /// 等级（用经验值兑换或计算）
        /// </summary>
        public int level { get; set; }

        /// <summary>
        /// 经验值（系统赠送）
        /// </summary>
        public int experience { get; set; }

        /// <summary>
        /// 血值（操作花费,增加）
        /// </summary>
        public int hp { get; set; }

        /// <summary>
        /// 魔法值（每天重置）
        /// </summary>
        public int mp { get; set; }

        #endregion

    }

    /// <summary>
    /// 用户的业务
    /// </summary>
    public class userC // : IDisposable
    {
        /// <summary>
        /// 匿名用户
        /// </summary>
        public static user guestUser { get { return new user() { Id = ObjectId.Parse("000000000000000000000001"), name = "匿名用户", email = "guest@asDigit.com" }; } }

        public static void initUserDB(){
            DataSession<MongoDataContext, user> db = new DataSession<MongoDataContext, user>();
            var q = new Dictionary<string,ObjectId>();
            q.Add("Id",ObjectId.Parse("000000000000000000000001"));
            if (db.Mquery.FindOne(new QueryDocument(q))==null)
            {
                db.Add(guestUser);
            }
        }

        //MongoSession<user> db = new MongoSession<user>();

        /// <summary>
        /// 创建一个默认的用户
        /// </summary>
        /// <returns></returns>
        public static user createDefault()
        {
            user user = new user();
            //this.sex = dictClass.get("default")["user_sex"];

            //默认经验值
            user.experience = dictClass.get("default").tryValue("user_experience", "0").ToInt().Value;

            //默认MP
            user.mp = 100;

            //默认血
            user.hp = 100;

            user.regDate = DateTime.Now;
            user.laterDate = DateTime.Now;

            user.limit = dictClass.get("default").tryValue("user_limit", "0").ToInt().Value; //huohhf
            user.group = dictClass.get("default").tryValue("user_group", ""); //huohhf

            return user;

        }



        public static DataSession<MongoDataContext, user> getDB()
        {
            DataSession<MongoDataContext, user> db = new DataSession<MongoDataContext, user>();
            return db;

        }
        /// <summary>
        /// 用户登录 内验证password
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <returns>登陆成功 或 用户名或密码错误</returns>
        public static bool login(string loginName, string password)
        {
            var db = new DataSession<MongoDataContext, user>();

                var userQ = db.Where(d => d.email == loginName && d.password == password.md5());
                //var userQ = db.Queryable.Where(d => d.email == loginName && d.password == password.md5());

                if (userQ.Any())
                {
                    user user = userQ.SingleOrDefault();

                    //当天第一次登录
                    if (user.laterDate.Date != DateTime.Now.Date)
                    {
                        user.mp = 100;
                        userC.update(user);
                    }

                    user.laterDate = DateTime.Now;

                    HttpContext.Current.Session["asDigit.client.user"] = userQ.SingleOrDefault();
                    return true;
                }
                return false;

        }

        /// <summary>
        /// 用户写session
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static void login(user user)
        {
            HttpContext.Current.Session["asDigit.client.user"] = user;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void logout()
        {
            HttpContext.Current.Session.Remove("asDigit.client.user");
        }

        /// <summary>
        /// 得到登录用户
        /// </summary>
        public static user loginUser
        {
            get
            {
                if (isLogin)
                {
                    return HttpContext.Current.Session["asDigit.client.user"] as user;
                }
                return guestUser;
            }
        }

        /// <summary>
        /// 用户修改密码
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// public static void upPassword(this user user, string password) by lys
        public static void upPassword(user user, string password)
        {
            var data = loginUser;
            if (data == null) new asMeishiException("请先登录!");
            var db = new DataSession<MongoDataContext, user>();
                data.password = password;
                db.Save(data);

        }
        public static user getById(ObjectId Id) {
            var db = new DataSession<MongoDataContext, user>();

            return db.GetById(Id);
        
        }
        /// <summary>
        /// 取得用户名
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string userName(ObjectId userId)
        {
            try
            {
                var db = new DataSession<MongoDataContext, user>();

                var user= db.GetById(userId);
                if (user == null) { return "未知"; }
                return user.name;
 
            }
            catch
            {
                return "未知";
            }
        }

        //取得用户等级
        public static level userLevel
        {
            get
            {
                var db = new DataSession<MongoDataContext, level>();

                    return db.Where(d=>d.code== loginUser.level).FirstOrDefault();

            }
        }

        /// <summary>
        /// 用户存储 并重写session;(进行经验转用户等级重设)
        /// </summary>
        /// <param name="user"></param>
        public static void update(user user)
        {
            if (!isLogin) return;

            //得到用户经验值
            int experience = user.experience;

            //得到相对应的等级
            var db = new DataSession<MongoDataContext, level>();
            
                //int levelCode = db.find(new { fraction = MongoDB.Op.LessThanOrEqual(experience) }, new { fraction = -1 }).First().code;
                int levelCode = db.Where(d => d.fraction <= experience).OrderByDescending(d => d.fraction).First().code;
                user.level = levelCode;


                DataSession<MongoDataContext, user> uc = new DataSession<MongoDataContext, user>();
            uc.Save(user);

            login(user);
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        public static bool isLogin
        {
            get { return (HttpContext.Current.Session["asDigit.client.user"] as user) != null; }
        }


    }

}